/*
 * This file is part of andExplorer, android.ovhoo.com
 * Copyright (C) 2007 Mohamed ZALIM <mzalim@ovhoo.com>
 *
 * andExplorer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * andExplorer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl.html>.
 */
package com.ovhoo.android.fiveexplore;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ovhoo.android.fiveexplore.R;
import com.ovhoo.android.file.AudioFilesFilter;
import com.ovhoo.android.file.CurentDirManager;
import com.ovhoo.android.file.FileInterface;
import com.ovhoo.android.media.AudioPlayerThread;
import com.ovhoo.android.media.MultimediaPlayer;


public class AudioPlayerDialog extends AbstractOpenFileDialog implements OnClickListener, SeekBar.OnSeekBarChangeListener{
	
	protected SeekBar seekBar;
	protected ImageButton seekBackward, startPlayBack, seekForward, pausePlayback, skipBackward, skipForward;
	protected TextView fileName, artistName, albumName, songName;
	
	protected MultimediaPlayer multimediaPlayer;
	protected ArrayList<FileInterface> playList;
	protected AudioPlayerThread thread;
	
	public AudioPlayerDialog(Context context, CurentDirManager fileManager, FileInterface file) {
		super(context, fileManager, file);
		//Thread player
		this.thread = new AudioPlayerThread(this);
		
		this.multimediaPlayer = MultimediaPlayer.getInstance();
		
		this.buildUI(); //Creation of the UI
		
		
		
		//generate Playlist
		this.buildPlayList();
		
		this.prepare();
		
		
		this.thread.start();
	}
	
	protected void buildUI(){
		LayoutInflater _inflater=this.getLayoutInflater();
		View _elementView = _inflater.inflate(R.layout.audioplayer, null);
		
		//get all dynamic ui components
		this.seekBar = (SeekBar) _elementView.findViewById(R.id.AUDIO_PLAYER_SEEK_BAR);
		
		this.seekBackward = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_SEEK_BACKWARD);
		this.startPlayBack = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_PLAYBACK_START);
		this.pausePlayback = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_PLAYBACK_PAUSE);
		this.seekForward = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_SEEK_FORWARD);
		this.skipForward = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_SKIP_FORWARD);
		this.skipBackward = (ImageButton) _elementView.findViewById(R.id.AUDIO_PLAYER_SKIP_BACKWARD);
		
		this.fileName = (TextView) _elementView.findViewById(R.id.AUDIO_PLAYER_FILE_NAME);
		this.artistName = (TextView) _elementView.findViewById(R.id.AUDIO_PLAYER_ARTIST_NAME);
		this.albumName = (TextView) _elementView.findViewById(R.id.AUDIO_PLAYER_ALBUM_NAME);
		this.songName = (TextView) _elementView.findViewById(R.id.AUDIO_PLAYER_SONG_NAME);
		
		//Addlisteners
		this.seekBar.setOnSeekBarChangeListener(this);
		
		this.seekBackward.setOnClickListener(this);
		this.startPlayBack.setOnClickListener(this);
		this.pausePlayback.setOnClickListener(this);
		this.seekForward.setOnClickListener(this);
		this.skipBackward.setOnClickListener(this);
		this.skipForward.setOnClickListener(this);
		
		this.updateButtons();
		this.setContentView(_elementView);
	}
	
	
	protected void updateButtons(){
		if (multimediaPlayer.isPlaying()){
			this.seekBackward.setEnabled(true);
			this.seekForward.setEnabled(true);
			this.pausePlayback.setVisibility(View.VISIBLE);
			this.startPlayBack.setVisibility(View.GONE);
		}
		else{
			this.seekBackward.setEnabled(false);
			this.seekForward.setEnabled(false);
			this.pausePlayback.setVisibility(View.GONE);
			this.startPlayBack.setVisibility(View.VISIBLE);
		}
	}
	
	protected void updateTags(){
		this.fileName.setText(this.file.getName());
		
		//ID3 tags using external library jaudio tagger
		String _artist = "-----";
		String _album = "-----";
		String _title = "-----";

		try {
			
			AudioFile _audioFile;
			_audioFile = AudioFileIO.read(this.file.getFile());
			
			Tag _tag = _audioFile.getTag();

			_artist= _tag.getFirstArtist();
			_artist= _tag.getFirstAlbum();
			_artist= _tag.getFirstTitle();
			
		} catch (CannotReadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TagException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ReadOnlyFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAudioFrameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (VerifyError e){
			e.printStackTrace();
		}
		
		if (_artist.equals("")){
			this.artistName.setText("-----");
		}
		else{
			this.artistName.setText(_artist);
		}
		
		if (!_album.equals("")){
			this.albumName.setText("-----");
		}
		else{
			this.albumName.setText(_album);
		}
		
		if (_title.equals("")){
			this.songName.setText("-----");
		}
		else{
			this.songName.setText(_title);
		}
	}
	
	protected void buildPlayList(){
		this.playList = fileManager.list(new AudioFilesFilter());
		
		Iterator<FileInterface> _itr = this.playList.iterator();
		
	    while (_itr.hasNext()) {
	      FileInterface _file = _itr.next();
	      if (this.file.equals(_file)){
	    	  this.file = _file;
	    	  break;
	      }
	    }
	}
	
	public void show(){
		super.show();
	}

	@Override
	public void onClick(View v) {
		if(v == this.seekBackward){
			this.onSeekBackward();
		}
		else if(v == this.startPlayBack){
			this.onStartPlayback();
		}
		else if(v == this.pausePlayback){
			this.onStartPlayback();
		}
		else if(v == this.seekForward){
			this.onSeekForward();
		}
		else if(v == this.skipForward){
			this.next();
		}
		if(v == this.skipBackward){
			this.prec();
		}
	}

	private void next() {
		int _pos = this.playList.indexOf(this.file);
		
		
		if (_pos == -1){
			this.multimediaPlayer.start();
		}
		else if (_pos +1 < this.playList.size()){
			this.file = this.playList.get(_pos+1);
			this.prepare();
			this.multimediaPlayer.start();
		}
		else{
			this.file = this.playList.get(0);
			this.prepare();
			this.multimediaPlayer.start();
		}
		this.updateButtons();
	}

	private void prec() {
		
		int _pos = this.playList.indexOf(this.file);
		
		
		if (_pos == -1){
			this.multimediaPlayer.start();
		}
		else if (_pos > 0){
			this.file = this.playList.get(_pos-1);
			this.prepare();
			this.multimediaPlayer.start();
		}
		else{
			this.file = this.playList.get(this.playList.size()-1);
			this.prepare();
			this.multimediaPlayer.start();
		}
		this.updateButtons();
		
	}

	private void onSeekForward() {
		// TODO Auto-generated method stub
	}

	private void onStartPlayback() {
		if (this.multimediaPlayer.isPlaying()){
			this.multimediaPlayer.pause();
		}
		else{
			this.multimediaPlayer.start();
		}
		
		this.updatePlayBack();
		this.updateButtons();
	}

	private void onSeekBackward() {
		// TODO Auto-generated method stub
		
	}

	public void updatePlayBack() {
		int _max = this.multimediaPlayer.getDuration();
		int _progress = this.multimediaPlayer.getCurrentPosition();
		
		seekBar.setMax(_max);
		seekBar.setProgress(_progress);
		

		if (_progress == _max && _progress != 0){
			this.next();
		}
	}
	
	
	public void prepare(){
		this.multimediaPlayer.prepare(this.getContext(),file);
		this.updatePlayBack();
		this.updateButtons();
		this.updateTags();
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		if (seekBar == this.seekBar){
			this.thread.suspend();
		}
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		if (seekBar == this.seekBar){
			this.multimediaPlayer.seekTo(seekBar.getProgress());
			this.thread.resume();
		}
		
	}
	
	public boolean isPlaying(){
		return this.multimediaPlayer.isPlaying();
	}
	
	
	
}
